#include "StdAfx.h"
#include "LogWriter.h"
#include <stdio.h>

void LogWriter::WriteToFile( TCHAR *iFName, TCHAR *iImgName, TCHAR *iMessage )
{	
	//get directory
	TCHAR buf[MAX_PATH];
	buf[0]=0;

	GetModuleFileName(NULL, buf, MAX_PATH);
	CString dir=buf;
	int ind=dir.ReverseFind('\\');
	dir.Delete(ind+1, dir.GetLength() - ind - 1);
	
	dir = DirName;


	//load template
	FILE *ftemplate = _tfopen(dir+_T("\\..\\log_template.htm"), _T("r"));
	if(!ftemplate) return;
	CString t;
	while(!feof(ftemplate))
	{
		_fgetts(buf, MAX_PATH, ftemplate);
		t += buf;
	}
	fclose(ftemplate);

	//replace templates
	t.Replace(_T("%img_path%"), iImgName);
	t.Replace(_T("%message_text%"), iMessage);


	//write to file	
	CString logpath = DirName;		
	logpath.ReleaseBuffer();

	if (!PathFileExists(logpath)) {
		CreateDirectory(logpath, NULL);
	}


	FILE *fout = _tfopen((logpath+iFName).GetBuffer(), _T("ab"));
	if(!fout) return;
	fwrite(t.GetBuffer(), sizeof(t[0]), t.GetLength(), fout);
	fclose(fout);
}


//------------------------------------------------------------------------------------------------------------------------------------
void LogWriter::GetUniqueFileName(TCHAR *iExt, TCHAR *oName)
{
	CString filename;

	//get date
	SYSTEMTIME systime;
	GetLocalTime(&systime);
	filename.Format(_T("%d_%d_%d_%d_%d_%d_%d_%d"),	systime.wDay, systime.wMonth, systime.wYear, 
												systime.wHour, systime.wMinute, systime.wSecond, 
												systime.wMilliseconds, rand());


/*
	//add temp file name
	CString temp;
	int id = GetTempFileName(DirName, filename, 0, temp.GetBuffer(500));
	temp.ReleaseBuffer();
	
	CString tmpname = filename.Left(3);


	//build output
	filename = temp;*/
	filename += _T(".");
	filename += iExt;


	//remove tmp file
	//temp.Format(_T("%s%s%x.tmp"), DirName, tmpname, id);
	//_tunlink(temp);


	//copy
	StrCpy(oName, filename);
}